<template>
    <div class="page">
        <top-select
            ref="topSelectRef"
            class="top-select"
            @on-confirm="onTopSelectConfirm"
            @on-open-dropdown="onTopSelectOpenDropdown"
        ></top-select>
        <xc-map
            query-type="lbs"
            :query-premises="lbsQueryData.premisesList"
            :query-addresses="lbsQueryForm.addresses"
            :distance-selected="distanceSelected"
        ></xc-map>
        <div class="page-bottom">
            <resource-info
                ref="resourceInfoRef"
                type="lbs"
                :detail="mediaResourceInfo"
                v-model:distance-selected="distanceSelected"
                @switch-address-popup="topSelectRef.getSearch()"
            ></resource-info>
            <div class="btn-box">
                <Button class="pre-btn" type="primary" plain hairline @click="goPre">
                    <span>上一步</span>
                </Button>
                <Button class="next-btn" type="primary" @click="goNext">
                    <span>下一步</span>
                </Button>
            </div>
        </div>
    </div>
</template>

<script name="productsLbs" lang="ts" setup>
import { watch, onMounted, ref, reactive, computed, onBeforeMount } from 'vue';
import { useRouter } from 'vue-router';
import { Button, Toast } from 'vant';
import { store } from '@/store';
import TopSelect from '@/components/TopSelect/index.vue';
import XcMap from '@/components/XCMap/index.vue';
import ResourceInfo from '@/views/products/components/ResourceInfo.vue';
import { MediaResourceItem, MediaResourceInfo } from '@/views/products/components/ResourceInfo.vue';
import { getLbsQueryData } from '@/api/lbs';
import {clearLoading, showLoading} from '@/api';

interface LbsAddress {
    longitude: number;
    latitude: number;
    radius: number;
}
interface LbsQueryForm {
    projectId: number;
    cityCode: number;
    areaCodes: Array<number>;
    addresses: Array<LbsAddress>;
    mediaTypes: Array<number>;
    premisesTypes: Array<string>;
    premisesPrices: Array<number>;
    premisesAges: Array<number>;
    inHouseRates: Array<number>;
    parkingNums: Array<number>;
    propertyFees: Array<number>;
}
interface Premises {
    id: string;
    name: string;
    lng: number;
    lat: number;
    positionLng: number;
    positionLat: number;
    province: string;
    city: string;
    area: string;
    address: string;
    type: string;
    accuratePrice: number;
    deliveryTime: string;
    inHouseRate: number;
    parkingNum: number;
    managementPrice: string;
    developersName: string;
    coveredHouseholdNum: number;
    coveredPeopleNum: number;
    buildingLevel: string;
    ownResourceTypes: Array<number>;
    buildingsNum: number;
    elevatorsNum: number;
    lifeTimestamp: number;
}
interface ResourceSummary {
    resourceSummary: object;
    mediaResourceSummaryList: Array<object>;
    resourceOwnerResourceSummaryList: Array<object>;
    projectPremisesList: Array<object>;
}
interface LbsQueryData {
    premisesList: Array<Premises>;
    resourceSummary: ResourceSummary;
}

const router = useRouter();
const storeApp = computed(() => {
    return store.state.app;
});
const storeHome = storeApp.value.home;
const storeSelectByLbs = computed(() => {
    return storeApp.value.selectByLbs;
});

const topSelectRef = ref(null);
const resourceInfoRef = ref(null);
const lbsQueryForm = reactive<LbsQueryForm>({
    projectId: storeHome.projectId,
    cityCode: storeHome.selectCity.id,
    areaCodes: [],
    addresses: [],
    mediaTypes: [],
    premisesTypes: [],
    premisesPrices: [],
    premisesAges: [],
    inHouseRates: [],
    parkingNums: [],
    propertyFees: [],
});
const lbsQueryData = reactive<LbsQueryData>({
    premisesList: [],
    resourceSummary: {
        resourceSummary: {},
        mediaResourceSummaryList: [],
        resourceOwnerResourceSummaryList: [],
        projectPremisesList: [],
    },
});
const mediaResourceInfo = reactive<MediaResourceInfo>({
    premisesNum: 0,
    pointNum: 0,
    coveredHouseholdNum: 0,
    coveredPeopleNum: 0,
    screen: {
        premisesNum: 0,
        pointNum: 0,
        coveredHouseholdNum: 0,
        coveredPeopleNum: 0,
    },
    lcd: {
        premisesNum: 0,
        pointNum: 0,
        coveredHouseholdNum: 0,
        coveredPeopleNum: 0,
    },
    frame: {
        premisesNum: 0,
        pointNum: 0,
        coveredHouseholdNum: 0,
        coveredPeopleNum: 0,
    },
});
const mediaResourceInfoEmpty = JSON.parse(JSON.stringify(mediaResourceInfo));
const distanceSelected = ref<number>(3);

let distanceTimeout;
watch(() => distanceSelected.value, () => {
    clearTimeout(distanceTimeout);
    lbsQueryForm.addresses = lbsQueryForm.addresses.map(address => {
        address.radius = distanceSelected.value * 1000;
        return address;
    });
    distanceTimeout = setTimeout(() => {
        getQueryData();
    }, 500);
});

const getQueryData = async () => {
    showLoading();
    try {
        if (!lbsQueryForm.addresses.length) {
            Toast('请选择地址');
            return;
        }
        const params = {
            ...lbsQueryForm,
        };
        const res = await getLbsQueryData(params);
        lbsQueryData.premisesList = res.premisesList.map((premises: Premises) => {
            premises.lng = premises.positionLng;
            premises.lat = premises.positionLat;
            return premises;
        });
        if (res.resourceSummary) {
            mediaResourceInfo.premisesNum = res.resourceSummary.resourceSummary.premisesNum;
            mediaResourceInfo.pointNum = res.resourceSummary.resourceSummary.pointNum;
            mediaResourceInfo.coveredHouseholdNum = res.resourceSummary.resourceSummary.coveredHouseholdNum;
            mediaResourceInfo.coveredPeopleNum = res.resourceSummary.resourceSummary.coveredPeopleNum;
            const mediaResourceInfoScreen = res.resourceSummary.mediaResourceSummaryList.find(mediaResourceSummary => {
                return mediaResourceSummary.mediaType === 1;
            });
            const mediaResourceInfoLcd = res.resourceSummary.mediaResourceSummaryList.find(mediaResourceSummary => {
                return mediaResourceSummary.mediaType === 2;
            });
            const mediaResourceInfoFrame = res.resourceSummary.mediaResourceSummaryList.find(mediaResourceSummary => {
                return mediaResourceSummary.mediaType === 3;
            });
            mediaResourceInfo.screen = {
                premisesNum: mediaResourceInfoScreen ? mediaResourceInfoScreen.premisesNum : '-',
                pointNum: mediaResourceInfoScreen ? mediaResourceInfoScreen.pointNum : '-',
                coveredHouseholdNum: mediaResourceInfoScreen ? mediaResourceInfoScreen.coveredHouseholdNum : '-',
                coveredPeopleNum: mediaResourceInfoScreen ? mediaResourceInfoScreen.coveredPeopleNum : '-',
            };
            mediaResourceInfo.lcd = {
                premisesNum: mediaResourceInfoLcd ? mediaResourceInfoLcd.premisesNum : '-',
                pointNum: mediaResourceInfoLcd ? mediaResourceInfoLcd.pointNum : '-',
                coveredHouseholdNum: mediaResourceInfoLcd ? mediaResourceInfoLcd.coveredHouseholdNum : '-',
                coveredPeopleNum: mediaResourceInfoLcd ? mediaResourceInfoLcd.coveredPeopleNum : '-',
            };
            mediaResourceInfo.frame = {
                premisesNum: mediaResourceInfoFrame ? mediaResourceInfoFrame.premisesNum : '-',
                pointNum: mediaResourceInfoFrame ? mediaResourceInfoFrame.pointNum : '-',
                coveredHouseholdNum: mediaResourceInfoFrame ? mediaResourceInfoFrame.coveredHouseholdNum : '-',
                coveredPeopleNum: mediaResourceInfoFrame ? mediaResourceInfoFrame.coveredPeopleNum : '-',
            };
        } else {
            Object.assign(mediaResourceInfo, mediaResourceInfoEmpty);
        }
    } catch (e) {
        console.error(e);
        return;
    } finally {
        clearLoading();
    }
};
const onTopSelectConfirm = (queryForm: LbsQueryForm) => {
    Object.assign(lbsQueryForm, queryForm);
    distanceSelected.value = 3;
    getQueryData();
};
const onTopSelectOpenDropdown = () => {
    resourceInfoRef.value.resetResourceInfoBodyHeight();
};
const goPre = () => {
    router.back();
};
const goNext = () => {
    if (!storeSelectByLbs.value.addresses||!storeSelectByLbs.value.addresses.length) {
        Toast('请选择地址');
        return;
    }
    storeSelectByLbs.value.addresses = storeSelectByLbs.value.addresses.map(address => {
        address.radius = distanceSelected.value * 1000;
        return address;
    });
    store.commit('app/setSelectByLbs', storeSelectByLbs.value);
    router.push({
        name: 'productsLbsStrategyCheck',
    });
};

const getCurrentLocation = async () => {
    Toast.loading({
        message: '加载中....',
        forbidClick: true,
        duration: 0, // 持续展示 toast
    });
    try {
        const mapGeolocation = new BMap.Geolocation();
        const mapGeocoder = new BMap.Geocoder();
        const selectByLbsNew = storeSelectByLbs.value;
        selectByLbsNew.addresses = [];
        selectByLbsNew.city = storeHome.selectCity;
        selectByLbsNew.tagBulidArr = {};
        selectByLbsNew.areaList = [];
        store.commit('app/setSelectByLbs', selectByLbsNew);
        mapGeolocation.getCurrentPosition((currentPosition) => {
            if (!currentPosition || currentPosition.address.city !== storeHome.selectCity.name) {
                Toast.clear();
                Toast('请选择地址');
                return;
            }
            mapGeocoder.getLocation(currentPosition.point, (locationInfo) => {
                Toast.clear();
                if (!locationInfo) {
                    Toast('请选择地址');
                    return;
                }
                lbsQueryForm.addresses = [{
                    longitude: locationInfo.point.lng,
                    latitude: locationInfo.point.lat,
                    radius: distanceSelected.value * 1000,
                }];
                selectByLbsNew.addresses = [{
                    cityName: currentPosition.address.city,
                    address: locationInfo.address,
                    title: locationInfo.address,
                    lng: locationInfo.point.lng,
                    lat: locationInfo.point.lat,
                    radius: distanceSelected.value * 1000,
                }];

                store.commit('app/setSelectByLbs', selectByLbsNew);
                getQueryData();
            });
        });
    } catch (error) {
        console.log(error);
        Toast.clear();
        Toast('请选择地址');
    } finally {
        Toast.clear();
    }
};

onBeforeMount(() => {
    getCurrentLocation();
});
onMounted(() => {
    // getQueryData();
});
</script>

<style lang="scss" scoped>
.page {
    position: relative;
    .top-select {
        position: absolute;
        left: 15px;
        z-index: 9;
        top: calc(10px + env(safe-area-inset-top));
        top: calc(10px + contain(safe-area-inset-top));
    }
    .page-bottom {
        width: 100%;
        background: #fff;
        border-radius: 12px 12px 0 0;
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 8;
        padding-bottom: env(safe-area-inset-bottom);
        padding-bottom: contain(safe-area-inset-bottom);
    }
    .btn-box {
        width: 100%;
        height: 50px;
        background: #fff;
        padding: 0 12px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .pre-btn {
            width: 120px;
        }
        .next-btn {
            width: 220px;
        }
        ::v-deep(.van-button) {
            height: 38px;
            font-size: 14px;
            color: #fff;
            border: none;
            border-radius: 6px;
            background: #e60044;
            &.van-button--hairline {
                color: #e60044;
                border-color: #e60044;
                background: #fff;
            }
            &.van-button--hairline::after {
                border-radius: 6px !important;
            }
        }
    }
}
</style>
